package com.yswee.framework.widget;

import com.yswee.framework.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.widget.ImageView;

public class RotateView extends ImageView {
	
	protected int mDuration;
	protected int mFrameCount;
	protected Animation mAnimation;

    public RotateView(Context context) {
        super(context);
    }

    public RotateView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initializeAttr(attrs);
    }
    
    protected void initializeAttr(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RotateView);
        mFrameCount = a.getInt(R.styleable.RotateView_frameCount, 12);  
        mDuration = a.getInt(R.styleable.RotateView_duration, 1000);
        a.recycle();

        if(getVisibility() == View.VISIBLE) {
        	startAnimation();
        }
    }

    public void startAnimation(int frameCount, int duration) {
    	mDuration = duration;
    	mFrameCount = frameCount;
    	if(mAnimation == null) {
    		mAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_rotateview);
    		mAnimation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    return (float)Math.floor(input * mFrameCount) / mFrameCount;
                }
            });
    	}
    	mAnimation.cancel();
    	mAnimation.reset();
    	mAnimation.setDuration(mDuration);
        startAnimation(mAnimation);
    }

    public void startAnimation() {
    	startAnimation(mFrameCount, mDuration);
    }
    
    public void stopAnimation() {
    	if(mAnimation != null) {
    		mAnimation.cancel();
    		mAnimation.reset();
    		mAnimation = null;
    	}
    }
    
    @Override
    public void setVisibility(int visibility) {
    	super.setVisibility(visibility);
    	if(visibility == View.VISIBLE) {
    		startAnimation();
    	} else {
    		stopAnimation();
    		clearAnimation();
    	}
    }
}